package com.tdx.blog_nowcoder.controller;

import com.tdx.blog_nowcoder.entity.MyEvent;
import com.tdx.blog_nowcoder.entity.User;
import com.tdx.blog_nowcoder.utils.RedisKeyUtils;
import com.tdx.blog_nowcoder.utils.event.EventProducer;
import com.tdx.blog_nowcoder.service.LikeService;
import com.tdx.blog_nowcoder.utils.DumpJSONToString;
import com.tdx.blog_nowcoder.utils.ThreadHostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

import static com.tdx.blog_nowcoder.constant.CommentReplyConstant.ENTITY_TYPE_COMMENT;
import static com.tdx.blog_nowcoder.constant.KafkaTopicConstant.TOPIC_LIKE;

@Controller
public class LikeController {
    @Autowired
    private LikeService likeService;

    @Autowired
    private ThreadHostHolder threadHostHolder;

    @Autowired
    private EventProducer eventProducer;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(path = "/like",method = RequestMethod.POST)
    @ResponseBody
    public String like(int entityType,int entityId,int entityUserId,int postId){
        User user = threadHostHolder.getUser();
        // 当前登入点赞
        likeService.like(user.getId(),entityType,entityId,entityUserId);
        // 获取（人数） 点赞的数量
        long likeCount = likeService.findEntityLikeCount(entityType,entityId);
        // 判断当前登入用户是否点过赞
        int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);

        // 返回的结果
        Map<String, Object> map = new HashMap<>();
        map.put("likeCount", likeCount);
        map.put("likeStatus", likeStatus);

        //点赞事件
        if (likeStatus == 1) {
            MyEvent event = new MyEvent()
                    .setTopic(TOPIC_LIKE)
                    .setUserId(threadHostHolder.getUser().getId())
                    .setEntityType(entityType)
                    .setEntityId(entityId)
                    .setEntityUserId(entityUserId) // 给谁点了赞
                    .setData("postId", postId);

            eventProducer.fireEvent(event);
        }

        if(entityType == ENTITY_TYPE_COMMENT) {
            // 计算帖子分数
            String redisKey = RedisKeyUtils.getPostScoreKey();
            redisTemplate.opsForSet().add(redisKey, postId);
        }

        return DumpJSONToString.getJsonString(200, null, map);
    }
}
